package com.fangwaii.core.authorization.auth;

import com.fangwaii.core.authorization.GatewayAuthenticationToken;
import com.fangwaii.core.authorization.GatewayAuthorizingRealm;
import com.fangwaii.core.authorization.IAuth;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

/**
 * @author lxc18
 * @date 2024/12/6 11:49
 * @description AuthService
 */
public class AuthService implements IAuth {
    private Subject subject;

    public AuthService() {
        // 1. 获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        // 初始化 SecurityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        GatewayAuthorizingRealm realm = new GatewayAuthorizingRealm();
        securityManager.setRealm(realm);

        // 绑定 SecurityManager
        ThreadContext.bind(securityManager);

        // 3. 得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        this.subject = SecurityUtils.getSubject();
    }

    @Override
    public boolean validate(String id, String token) {
        //验证过程
        //生成token，然后用
        try {
            subject.login(new GatewayAuthenticationToken(id,token));
            return subject.isAuthenticated();
        }
        finally {
            // 退出
            subject.logout();
        }

    }
}
